import struct, socket, time, threading


class Client:
    def __init__(self):
        address = ('localhost', 9999)
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect(address)
        
        threadHeartbeat = threading.Thread(target=self.heartbeat)
        threadHeartbeat.setDaemon(True)
        threadHeartbeat.start()
        threadsendout = threading.Thread(target=self.sendout)
        threadsendout.setDaemon(True)
        threadsendout.start()
        threadreceive = threading.Thread(target=self.receive)
        threadreceive.setDaemon(True)
        threadreceive.start()

    def __del__(self):
        self.client.close() 

    def heartbeat(self):
        while True:
            time.sleep(0.05)
            self.client.send(struct.pack('=I', 0))

    def sendout(self):
        i=0
        while True:
            i+=1
            content = struct.pack('=id', i, 1.0/i)
            content = struct.pack('=i', len(content)) + content
            time.sleep(2)
            self.client.send(content)

    def receive(self):
        while True:
            time.sleep(0.5)
            lenData = struct.unpack('=i', self.client.recv(struct.calcsize('=I')))
            data = self.client.recv(lenData[0])
            self.client.send(struct.pack('=i', -1)) # 收到后需要回信才可以接收下一条内容
            #print("data:",data)
            print("data:", struct.unpack('=id', data))


if __name__ == "__main__":
    client = Client()
    time.sleep(60)

